package sctu.edu.java.year2016.team02.project.service.UI;

import sctu.edu.java.year2016.team02.project.service.SQLOperate;
import sctu.edu.java.year2016.team02.project.service.problem.ServerProblem;

import javax.swing.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Eoly on 2016/6/16.
 */
//当服务端被访问时，创建单个进程单个套接字与之连接并进行各种操作
public class SocketRunnable implements Runnable {
    private Socket socket;
    private ServerProblem serverProblem;
    private JTextArea state;

    public SocketRunnable(Socket socket, JTextArea state) {
        this.state = state;
        this.socket = socket;
        serverProblem = new ServerProblem(socket);
    }
    //进行输出流
    private void Output(Object obj) throws IOException {
        if(socket.isConnected()&&!socket.isClosed()){
            ObjectOutputStream output= new ObjectOutputStream(socket.getOutputStream());
            output.writeObject(obj);
            output.flush();
        }
    }
    //进行输出流
    private Object Input() throws IOException, ClassNotFoundException {
        if(socket.isConnected()&&!socket.isClosed()){
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
            return input.readObject();
        }
        return null;
    }
    //在主界面添加提示文字
    public void setStateText(String text,String user) {
        state.setText(state.getText() + " [" + user + "] " + "[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] " +  text + "\n");
                state.setCaretPosition(state.getText().length());
    }

    //对获得客户端的所有命令进行操作
    public void setOperate(Socket socket,int temp) throws IOException {
        try {
            int option = temp;///命令编号
            switch (option){
                case ServerProblem.DELETE: {
                    setStateText("获取命令：删除", socket.getInetAddress().toString());
                    Output(ServerProblem.DELETE);
                    List list = (List) Input();
                    setStateText("获取删除操作 参数：" + list, socket.getInetAddress().toString());
                    SQLOperate.delete((String) list.get(0), (String) list.get(1));
                    Output("删除命令执行成功");
                    setStateText("删除命令执行成功", socket.getInetAddress().toString());
                    break;
                }
                case ServerProblem.INSERT:{
                    Output(ServerProblem.INSERT);
                    setStateText("获取命令：插入", socket.getInetAddress().toString());
                    List list = (List) Input();
                    String TableName = (String)list.get(0);
                    String[] name = (String[])list.get(1);
                    String[] value = (String[])list.get(2);
                    setStateText("获得参数成功", socket.getInetAddress().toString());
                    Output(SQLOperate.insert(TableName, name, value));
                    setStateText("获得插入结果并返回成功", socket.getInetAddress().toString());
                    break;
                }
                case ServerProblem.INSERT_KEY:{
                    setStateText("获取命令：插入", socket.getInetAddress().toString());
                    Output(ServerProblem.INSERT_KEY);
                    List list = (List) Input();
                    String TableName = (String)list.get(0);
                    String[] name = (String[])list.get(1);
                    String[] value = (String[])list.get(2);
                    int key = (int)list.get(3);
                    setStateText("获得参数成功", socket.getInetAddress().toString());
                    Output(SQLOperate.insert(TableName, name, value, key));
                    setStateText("获得查询结果并返回成功", socket.getInetAddress().toString());
                    break;
                }
                case ServerProblem.SELECT: {
                    Output(ServerProblem.SELECT);
                    setStateText("获取命令：查找", socket.getInetAddress().toString());
                    List list = (List) Input();
                    String TableName = (String)list.get(0);
                    String[] fieldname = (String[])list.get(1);
                    String[] value = (String[])list.get(2);
                    boolean isLike = (boolean)list.get(3);
                    setStateText("获得参数成功", socket.getInetAddress().toString());
                    Output(SQLOperate.select(TableName, fieldname, value, isLike));
                    setStateText("获得查询结果并返回成功", socket.getInetAddress().toString());
                    break;
                }
                case ServerProblem.UPDATE_INT:{
                    Output(ServerProblem.UPDATE_INT);
                    setStateText("获取命令：修改", socket.getInetAddress().toString());
                    List list = (List) Input();
                    String TableName = (String)list.get(0);
                    String name = (String)list.get(1);
                    String key = (String)list.get(2);
                    String keyfield = (String)list.get(3);
                    int value = (int)list.get(4);
                    setStateText("获得参数成功", socket.getInetAddress().toString());
                    SQLOperate.update(TableName, name, key, keyfield, value);
                    Output("修改成功");
                    setStateText("修改成功", socket.getInetAddress().toString());
                    break;
                }
                case ServerProblem.UPDATE_STRING:{
                    Output(ServerProblem.UPDATE_STRING);
                    setStateText("获取命令：修改", socket.getInetAddress().toString());
                    List list = (List) Input();
                    String TableName = (String)list.get(0);
                    String name = (String)list.get(1);
                    String key = (String)list.get(2);
                    String keyfield = (String)list.get(3);
                    String value = (String)list.get(4);
                    setStateText("获得参数成功", socket.getInetAddress().toString());
                    SQLOperate.update(TableName, name, key, keyfield, value);
                    Output("修改成功");
                    setStateText("修改成功", socket.getInetAddress().toString());
                    break;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
            setStateText("执行数据库操作失败:"+e.getMessage(),"/local");
            if(!socket.isClosed()){
                Output("执行数据库操作失败:"+e.getMessage());
                socket.close();
            }
        }
    }

    @Override
    public void run() {
        setStateText("连接成功...",socket.getInetAddress().toString());
        boolean isConn = socket.isConnected();
        while (isConn && StartAndClose.isStart) {
            if (!socket.isConnected()) break;
            try {
                Integer temp=(Integer)Input();
                setOperate(socket,temp);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {

            } catch (ClassNotFoundException e) {

            }
        }
        try {
            if (!socket.isConnected()) {
                socket.close();
                setStateText("连接断开...",socket.getInetAddress().toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
